package com.poisonh.unifiedauth.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.adapter.RvPassWdAdapter;
import com.poisonh.unifiedauth.dialog.AddPasswordBoxDialogFragment;
import com.poisonh.unifiedauth.dialog.PassWdDialogFragment;
import com.poisonh.unifiedauth.model.PassWdModel;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.GsonUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PinyinComparator;
import com.poisonh.unifiedauth.utils.PinyinUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.widget.EditTextWithDel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 密码箱
 * Created by PoisonH on 2016/6/24.
 */

public class PassWordBoxActivity extends BaseActivity implements
        View.OnClickListener, RvPassWdAdapter.OnItemClickLitener,
        AddPasswordBoxDialogFragment.ChangeListener,
        PassWdDialogFragment.DeleteListener
{
    private XRecyclerView mXRecyclerView;
    private EditTextWithDel mEtSearchName;
    private List<PassWdModel> mPassBoxList;
    private RvPassWdAdapter mRvPassWdAdapter;
    private List<PassWdModel> mSortList;
    private boolean isLoad = false;
    private int pos = -1;
    private int page = 1;

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_passwordbox);
        initTitleView();
        initView();
    }

    @Override
    protected void initView()
    {
        setTitleTxt("密码箱");
        setRightBtnBg(R.mipmap.password_add);

        mPassBoxList = new ArrayList<>();
        mSortList = new ArrayList<>();
        mTvRight.setText("添加");
        mRightBtn.setVisibility(View.GONE);

        mEtSearchName = (EditTextWithDel) findViewById(R.id.et_search);
        mXRecyclerView = (XRecyclerView) findViewById(R.id.xrv_passwdbox);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mXRecyclerView.setLayoutManager(layoutManager);
        mXRecyclerView.setPullRefreshEnabled(true);
        mTvRight.setOnClickListener(this);
        mTvRight.setVisibility(View.VISIBLE);
        mLeftBtn.setOnClickListener(this);
        initEvents();
        setAdapter();
        getPassWdBox(page);
        mXRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener()
        {
            @Override
            public void onRefresh()
            {
                getPassWdBox(1);
                isLoad = false;
            }

            @Override
            public void onLoadMore()
            {
                page += 1;
                getPassWdBox(page);
                isLoad = true;
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.tv_right_txt:
                AddPasswordBoxDialogFragment addPasswordBoxDialogFragment = new AddPasswordBoxDialogFragment();
                addPasswordBoxDialogFragment.show(getFragmentManager(), "");
                break;
            case R.id.ib_left_btn:
                finish();
                break;
        }
    }

    private void initEvents()
    {
        //根据输入框输入值的改变来过滤搜索
        mEtSearchName.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s)
            {
            }
        });
    }


    /**
     * 获取密码箱
     */
    private void getPassWdBox(int page)
    {

        HttpParams params = new HttpParams();
        params.put("id",mStrUserId);
        params.put("page", page + "");
        params.put("size", "10");
        params.put("token", mStrUserToken);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETBOXLIST, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                Message msg = Message.obtain();
                msg.obj = response;
                mHandler.sendMessage(msg);
                Log.d("PassWordBoxActivity", "response" + response);
                mXRecyclerView.refreshComplete();
                mXRecyclerView.loadMoreComplete();

            }

            @Override
            public void onFailure(String failReason)
            {
                mXRecyclerView.refreshComplete();
                mXRecyclerView.loadMoreComplete();
            }
        });
    }


    /**
     * 设置数据适配器
     */
    private void setAdapter()
    {
        mRvPassWdAdapter = new RvPassWdAdapter(this);
        mXRecyclerView.setAdapter(mRvPassWdAdapter);
        mRvPassWdAdapter.setOnItemClickLitener(this);
    }

    /**
     * 单击事件监听
     *
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(View view, int position)
    {
        pos = position;
        PassWdDialogFragment fragment = new PassWdDialogFragment();
        Bundle mBundle = new Bundle();
        mBundle.putString("ACCOUNT", mSortList.get(position).getACCOUNT());
        mBundle.putString("PASSWORD", mSortList.get(position).getPASSWORD());
        mBundle.putString("URL", mSortList.get(position).getURL());
        mBundle.putString("NAME", mSortList.get(position).getNAME());
        mBundle.putString("ID", mSortList.get(position).getID());
        fragment.setArguments(mBundle);
        fragment.show(getFragmentManager(), "");

    }


    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
           // String mId=mStrId;
            mPassBoxList = GsonUtils.parsePassWdBoxData((String) msg.obj,mStrUserId);
            if (isLoad)
            {
                if (mPassBoxList.size() > 0)
                {
                    mPassBoxList = filledData(mPassBoxList);
                    Collections.sort(mPassBoxList, new PinyinComparator());
                    mRvPassWdAdapter.notif(mPassBoxList);
                } else
                {
                    ToastUtils.showToast(PassWordBoxActivity.this, "没有更多数据");
                    mXRecyclerView.setLoadingMoreEnabled(false);
                }
            } else
            {
                if (mPassBoxList.size() > 0)
                {
                    mSortList.clear();
                    mPassBoxList = filledData(mPassBoxList);
                    Collections.sort(mPassBoxList, new PinyinComparator());
                    mRvPassWdAdapter.update(mPassBoxList);
                } else
                {
                    ToastUtils.showToast(PassWordBoxActivity.this, "没有更多数据");
//                    mSortList.clear();
//                    mRvPassWdAdapter.notifyDataSetChanged();
                    mXRecyclerView.setLoadingMoreEnabled(false);
                }
            }

        }
    };

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr)
    {
        List<PassWdModel> mSortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr))
        {
            mSortList = mPassBoxList;
        } else
        {
            mSortList.clear();
            for (PassWdModel passWdModel : mPassBoxList)
            {
                String name = passWdModel.getNAME();
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase()))
                {
                    mSortList.add(passWdModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinComparator());
        mRvPassWdAdapter.update(mSortList);
    }

    private List<PassWdModel> filledData(List<PassWdModel> data)
    {
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < data.size(); i++)
        {
            PassWdModel model = new PassWdModel();
            model.setACCOUNT(data.get(i).getACCOUNT());
            model.setPASSWORD(data.get(i).getPASSWORD());
            model.setStart(data.get(i).isStart());
            model.setTIME(data.get(i).getTIME());
            model.setURL(data.get(i).getURL());
            model.setNAME(data.get(i).getNAME());
            model.setID(data.get(i).getID());

            //汉字转拼音
            String pinyin = PinyinUtils.getPingYin(data.get(i).getNAME());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            if (sortString.matches("[A-Z]"))
            {
                model.setmStrFirstLetter(sortString.toUpperCase());
                if (!indexString.contains(sortString))
                {
                    //添加到数组中去
                    indexString.add(sortString);
                }
            } else
            {
                model.setmStrFirstLetter("#");
            }

            mSortList.add(model);
        }
        Collections.sort(indexString);
        return mSortList;
    }

    @Override
    public void onDeleteListener(boolean change)
    {
        if (change == true)
        {

            mSortList.remove(pos);
            mRvPassWdAdapter.update(mSortList);
        }
    }


    @Override
    public void onChangeListener(boolean change)
    {
        if (change == true)
        {
            //mSortList.clear();
            getPassWdBox(1);
            isLoad = false;
        }
    }

}
